package com.epam.iunna.bookshop.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.epam.iunna.bookshop.model.util.ConnectionsPool;
import com.epam.iunna.bookshop.model.util.DBUtils;

public class OrderItemDao {

    public void addOrderItemList(List<OrderItem> orderItemList)
            throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("insert into orderitem (orderid,itemid,quantity) values (?,?,?)");
                for (OrderItem orderItem : orderItemList) {
                    statement.setLong(1, orderItem.getOrderId());
                    statement.setLong(2, orderItem.getItemId());
                    statement.setLong(3, orderItem.getQuantity());
                    statement.addBatch();
                }

                statement.executeBatch();
            } else {
                throw new SQLException("Cannot obtain db connection.");
            }
        } finally {
            DBUtils.closeConnection(connection, statement, null);
        }
    }

    public void delByOrderID(Long orderID) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.

                statement = connection
                        .prepareStatement("delete from orderitem where orderid= ? ");
                statement.setLong(1, orderID);

                statement.executeUpdate();
            } else {
                throw new SQLException("Cannot obtain db connection.");
            }
        } finally {
            DBUtils.closeConnection(connection, statement, null);
        }
    }

}